package cn.yitun.chat.yitunserverrunsingleboot.chat.common.interceptor;

import cn.yitun.chat.yituncommonmessage.ExceptionEnum;
import cn.yitun.chat.yituncommonmessage.YitunException;
import cn.yitun.chat.yituncommonutil.YitunStringUtil;
import cn.yitun.chat.yituncommonweb.util.YitunHttpUtil;
import cn.yitun.chat.yitunservercommonlib.basebean.web.RequestInfoDto;
import cn.yitun.chat.yitunservercommonlib.constant.Constants;
import cn.yitun.chat.yitunservermanagecore.general.bridge.auth.manager.AuthManager;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * token拦截器
 */
@Component
@Slf4j
public class TokenInterceptor implements HandlerInterceptor {

//    @Autowired
//    private RedisManager redisManager;

    @Autowired
    private AuthManager authManager;

    /**
     * 前置拦截器
     */
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) {
        log.info("请求：{} , {}", httpServletRequest.getRequestURI(), httpServletRequest.getRequestURL().toString());
        // 获取校验参数
        String token = YitunHttpUtil.getRequestParam(httpServletRequest, Constants.TOKEN);
        // 检测ip
        checkIp(httpServletRequest, token);
        // 获取token并验证
        return checkToken(token, httpServletRequest);
    }

    /**
     * 检测redis token方案
     *
     * @param jwtToken           token
     * @param httpServletRequest request
     */
    private boolean checkToken(String jwtToken, HttpServletRequest httpServletRequest) {


        // 根据uid cid 从缓存中获取当前登录用户
        if (YitunStringUtil.isEmpty(jwtToken) || jwtToken.equals("null")) {
            throw new YitunException(ExceptionEnum.VERIFY_PARAM_INCOMPLETE);
        }

        if(!authManager.isAuth(jwtToken))
            throw new YitunException(ExceptionEnum.TOKEN_NULL);

        // 将 当前登录用户 放入request
//        httpServletRequest.setAttribute(Constants.CURRENT_LOGIN_USER, jwtUserDto);
        return true;
    }

    /**
     * 设置请求IP 参数
     *
     * @param request
     */
    private void checkIp(HttpServletRequest request, String jwtToken) {
        String ipAddr = YitunHttpUtil.getIpAddr(request);
        RequestInfoDto requestInfoDTO = new RequestInfoDto();
        // 设置请求值
        requestInfoDTO.setUrl(request.getRequestURI());
        requestInfoDTO.setIp(ipAddr);
        requestInfoDTO.setJwtToken(jwtToken);
        //todo 参数
        //放入attr
        request.setAttribute(Constants.REQUEST_INFO, requestInfoDTO);
//        logger.info("访问ip:" + ipAddr);
    }




}
